//
//  AudioPlayer.m
//  Session--Test
//
//  Created by lanou3g on 15/12/17.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "AudioPlayer.h"
@interface AudioPlayer()
/** 系统音乐播放类 */
@property (nonatomic, strong) AVPlayer *musicPlayer;
/** 是否正在播放 */
@property (nonatomic, assign) BOOL selfIsPlaying;
/** 定时器 */
@property (nonatomic, strong) NSTimer *timer;
@end
static AudioPlayer *player = nil;
@implementation AudioPlayer
- (BOOL)isPlaying {
    return self.selfIsPlaying;
}
/*---------------------------------------
 单例
 --------------------------------------- */
+ (instancetype) shareAudioPlayer {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[AudioPlayer alloc] init];
        //接收播放结束的通知
        [[NSNotificationCenter defaultCenter] addObserver:player selector:@selector(endMusicAction) name:AVPlayerItemFailedToPlayToEndTimeNotification object:nil];
    });
    return player;
}

/*---------------------------------------
 播放结束的通知
 --------------------------------------- */
- (void)endMusicAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(playToTheEnd:)]) {
        //回调播放结束的消息
        [self.delegate playToTheEnd:self];
    }
}

/*---------------------------------------
 播放/暂停
 --------------------------------------- */
- (void)palyOrPause {
    if (self.isPlaying) {
        [self playPause];
    } else {
        [self playAudio];
    }
}

/*---------------------------------------
 播放
 --------------------------------------- */
- (void)playAudio {
    [self.musicPlayer play];
    self.selfIsPlaying = YES;
    if (self.timer) {
        return;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

/*---------------------------------------
 暂停
 --------------------------------------- */
- (void)playPause {
    [self.musicPlayer pause];
    self.selfIsPlaying = NO;
    [self.timer invalidate];
    self.timer = nil;
}

/*---------------------------------------
 定时器方法
 --------------------------------------- */
- (void)timerAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(playToWhere:player:)]) {
        //获取当前时间
        float time = self.musicPlayer.currentTime.value / self.musicPlayer.currentTime.timescale;
        //代理回调
        [self.delegate playToWhere:time player:self];
    }
}

/*---------------------------------------
 给url播放
 --------------------------------------- */
- (void)playAudioWithUrl:(NSString *)url {
    //判断url并检查类型
    if (!url && ![url isKindOfClass:[NSString class]]) {
        return;
    }
    if (self.musicPlayer.currentItem) {
        [self.musicPlayer removeObserver:self forKeyPath:@"status" context:nil];
    }
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [self.musicPlayer replaceCurrentItemWithPlayerItem:item];
}

/*---------------------------------------
 观察者方法
 --------------------------------------- */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if (![keyPath isEqualToString:@"status"]) {
        return;
    }
    AVPlayerItemStatus status = [change[@"new"] integerValue];
    switch (status) {
        case AVPlayerItemStatusUnknown:
            break;
        case AVPlayerItemStatusFailed:
            break;
        case AVPlayerItemStatusReadyToPlay:
            [self playAudio];
            break;
        default:
            break;
    }
}

/*---------------------------------------
 设置音量
 --------------------------------------- */
- (void)setVolume:(float)volume {
    if (volume < 0 || volume > 1) {
        return;
    }
    self.musicPlayer.volume = volume;
}

/*---------------------------------------
 从某个时刻开始播放
 --------------------------------------- */
- (void)seekTimeToPlay:(float)time {
    if (self.isPlaying) {
        [self playPause];
    }
    [self.musicPlayer seekToTime:CMTimeMakeWithSeconds(time, self.musicPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
        [self playAudio];
    }];
}

/*---------------------------------------
 懒加载
 --------------------------------------- */
- (AVPlayer *)musicPlayer {
    if (!_musicPlayer) {
        _musicPlayer = [[AVPlayer alloc] init];
        _musicPlayer.volume = 0.5;
    }
    return _musicPlayer;
}

/*---------------------------------------
 移除监听
 --------------------------------------- */
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:AVPlayerItemDidPlayToEndTimeNotification];
}

@end
